package com.ruoyi.file.controller;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.file.component.PublishLayerProcess;
import com.ruoyi.file.domain.*;
import com.ruoyi.file.service.ITblFileDataService;
import com.ruoyi.framework.minio.MinioService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.gis.domain.GisLayer;
import com.ruoyi.gis.service.IDatasetRasterService;
import com.ruoyi.gis.vo.CollectAddImageDto;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.file.service.ITblFileService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 文件管理Controller
 *
 * @author rww
 * @date 2023-09-05
 */
@RestController
@RequestMapping("/tlbfile/file")
public class TblFileController extends BaseController
{

    @Autowired
    private ITblFileService tblFileService;
    @Autowired
    private ITblFileDataService tblFileDataService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private PublishLayerProcess publishLayerProcess;
    @Autowired
    private MinioService minioService;
    @Autowired
    private RuoYiConfig ruoYiConfig;


    /**
     * 查询文件管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request,TblFile tblFile)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(request);
        tblFile.setUserId(loginUser.getUserId());
        List<TblFile> list = tblFileService.selectTblFileList(tblFile);
        return getDataTable(list);
    }

    @GetMapping("/list/all")
    public AjaxResult listAll(HttpServletRequest request,TblFile tblFile)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        tblFile.setUserId(loginUser.getUserId());
        List<TblFile> list = tblFileService.selectTblFileList(tblFile);
        return AjaxResult.success(list);
    }

    @GetMapping("/list/all/folder")
    public AjaxResult listAllFolder(HttpServletRequest request,TblFile tblFile)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        tblFile.setUserId(loginUser.getUserId());
        tblFile.setFileType(TblFile.type_folder);
        List<TblFile> list = tblFileService.selectTblFileList(tblFile);
        return AjaxResult.success(list);
    }


    /**
     * 导出文件管理列表
     */
    @Log(title = "文件管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TblFile tblFile)
    {
        List<TblFile> list = tblFileService.selectTblFileList(tblFile);
        ExcelUtil<TblFile> util = new ExcelUtil<TblFile>(TblFile.class);
        util.exportExcel(response, list, "文件管理数据");
    }

    /**
     * 获取文件管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tblFileService.selectTblFileById(id));
    }

    @GetMapping(value = "/info/extend/{id}")
    public AjaxResult getExtendInfoInfo(@PathVariable("id") Long id)
    {
        TblFile tblFile = tblFileService.selectTblFileDetailById(id);
        return success(tblFile);
    }

    @GetMapping(value = "/info/extend/data/{fileId}")
    public TableDataInfo listFileData(@PathVariable("fileId") Long fileId,TblFileData tblFileData)
    {
        startPage();
        tblFileData.setFileId(fileId);
        List<TblFileData> list = tblFileDataService.selectTblFileDataList(tblFileData);
        return getDataTable(list);
    }

//    SELECT a.file_info::json->>'TJGCMC'
//    FROM tbl_file_data a where a.file_id = 1723996421130653696
//    GROUP BY  a.file_info::json->>'TJGCMC';
    @GetMapping(value = "/info/extend/data/field/{fileId}/{field}")
    public AjaxResult getExtendInfoInfo(@PathVariable("fileId") Long fileId,
                                        @PathVariable("field") String field)
    {
        List<Map<String, Object>> values = tblFileDataService.selectTblFileDataByIdAndField(fileId,field);
        return success(values);
    }

    /**
     * 修改文件管理
     */
    @Log(title = "文件管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TblFile tblFile)
    {
        return toAjax(tblFileService.updateTblFile(tblFile));
    }

    /**
     * 删除文件管理
     */
    @Log(title = "文件管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tblFileService.deleteTblFileByIds(ids));
    }


    //新增文件夹
    @PostMapping("addFolder")
    public AjaxResult addFileFolder(HttpServletRequest request,
                                   @RequestBody FileAddFolderDto fileAddFolderDto) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        Long userId = loginUser.getUserId();
        TblFile folder = tblFileService.addFolder(
                userId,fileAddFolderDto.getPid(),fileAddFolderDto.getFileName());
        if(folder!=null){
            return AjaxResult.success(folder);
        }else {
            return AjaxResult.error("添加目录失败");
        }
    }

    /**
     * 新增文件管理
     */
    @Deprecated
    @Log(title = "文件管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult saveFile(HttpServletRequest request,@RequestBody FileAddDto fileAddDto) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        List<FilePublishDto> filePublishDtos = tblFileService.
                saveFile(loginUser, fileAddDto);
        publishLayerProcess.publishLayer(filePublishDtos);
        return AjaxResult.success();
    }
    //从影像导入
    @PostMapping("addRasterImages")
    public AjaxResult addRasterImages(HttpServletRequest request,
                                @RequestBody FileAddRasterImageDto dto)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if(dto.getDataIds()==null||dto.getDataIds().size()==0){
            return AjaxResult.error("dataIds参数错误");
        }
        tblFileService.addRasterImages(loginUser,dto);
        return AjaxResult.success();
    }


    @PostMapping("publish/file/{id}")
    public AjaxResult publishFile(HttpServletRequest request,
            @PathVariable Long id) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        tblFileService.publishFile(id,loginUser);
        return AjaxResult.success();
    }


    //手动发布
    @PostMapping("publish")
    public AjaxResult publish(HttpServletRequest request,
                              @RequestBody FilePublishDto filePublishDto) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        publishLayerProcess.sendPublishLayerMessage(filePublishDto);
        return AjaxResult.success();
    }

    //撤销发布
    @PutMapping("publish/cancel/{id}")
    public AjaxResult publish(HttpServletRequest request,@PathVariable Long id) throws IOException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        boolean b = publishLayerProcess.cancelFilePublish(id);
        return b?AjaxResult.success("撤销成功"):AjaxResult.error("撤销失败");
    }

    //文件预览地址
    @GetMapping("/preview/{id}")
    public AjaxResult getFilePreviewUrl(@PathVariable("id") Long id) {
//        minioService.getBuckctObjectUrl()
        TblFile projectFile = tblFileService.selectTblFileById(id);
        if (projectFile == null) {
            return AjaxResult.error("参数错误");
        }
        String buckctObjectUrl = minioService.getBucketObjectUrl(projectFile.getBucket(),
                projectFile.getObjectName());
        JSONObject data = new JSONObject();
        data.put("fullfilename", projectFile.getFileName());
        data.put("url", buckctObjectUrl);//这个url是加密过的了
        if(buckctObjectUrl!=null){
            String url = Base64Utils.encodeToString(buckctObjectUrl.getBytes(StandardCharsets.UTF_8));//Base64Utils.encodeToUrlSafeString(buckctObjectUrl.getBytes(StandardCharsets.UTF_8));//buckctObjectUrl;//+"&fullfilename="+projectFile.getName();
            data.put("previewUrl", ruoYiConfig.getFilePreviewServer() + "/onlinePreview?url=" + url
                    + "&fileName=" + projectFile.getFileName());
        }
        //Base64Utils.encodeToString(url.getBytes()));//URLEncoder.encode(url));
        return AjaxResult.success("成功", data);
    }


}
